import React, { useMemo, useState } from "react";
import { Row, Col } from "antd";
import SearchTree from "@/biz-components/search-tree";
import { CreateModalList } from "../with-list";
import AsyncTree from "@/biz-components/async-tree";
import { WithTreeListProps } from "hoc-form";
const WithListComp = CreateModalList({});
const WithTreeList: React.FC<WithTreeListProps> = (props) => {
  const nodeRef = React.useRef();
  const {
    modalfiledConfig,
    modalformConfigs,
    modalCode,
    paramsMap,
    noModal,
    url,
    events,
    nodeKeys = ["code"],
    pageApi,
    searchCode,
    async = false,
    noQueryKeys = false,
  } = props;
  const [treeNode, setTreeNode] = useState<any>(async ? { isRoot: true } : {});
  const [changeTree, setChangeTree] = useState<any>();
  const [tableParams, settableParams] = useState<any>();
  const handleSelectNode = (node: any) => {
    if (!node) {
      settableParams(null);
      return;
    }
    setTreeNode(node);
    nodeRef.current = node;
    const params = {};
    if (paramsMap && paramsMap.length > 0 && node) {
      paramsMap.forEach((key, index) => {
        params[key] = node[nodeKeys[index]] || null;
      });
    }
    settableParams({ ...params });
  };
  const changeTreeData = () => {
    setChangeTree(!changeTree);
  };
  const map = {
    effects() {
      if (modalformConfigs) {
        modalformConfigs({
          treeNode: nodeRef,
        });
      }
    },
  };

  return (
    <Row>
      <Col span={6} className="leftTree tree">
        {!async ? (
          <SearchTree
            onSelect={handleSelectNode}
            api={{
              url,
            }}
          />
        ) : (
          <AsyncTree
            url={url}
            nodeInfo={treeNode}
            treeNodeClick={handleSelectNode}
            changeTree={changeTree}
            changeTreeData={changeTreeData}
          />
        )}
      </Col>
      <Col span={16}>
        <Row>
          当前节点:
          {`${(treeNode && treeNode.name) || ""}-${
            (treeNode && treeNode.code) || ""
          }`}
        </Row>
        <WithListComp
          modalfiledConfig={modalfiledConfig}
          modalformConfigs={map}
          noModal={noModal}
          modalCode={modalCode}
          events={events}
          noQueryKeys={noQueryKeys}
          extraPrams={tableParams}
          pageApi={pageApi}
          pageCode={searchCode}
        />
      </Col>
    </Row>
  );
};

export default WithTreeList;
